package com.example.viewtest.draw_6;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.example.viewtest.Utils;

/**
 * 饼图
 *
 */
public class PieChartView extends View {
    private final static int[] COLORS = {Color.DKGRAY, Color.GRAY, Color.LTGRAY, Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN, Color.MAGENTA};
    private static final float PAINDING = Utils.db2px(20);

    private RectF rectF = new RectF();
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private float[] sweepAngles = {50, 100, 80, 50, 80};

    private int offsetIndex = 1;
    private float offset = Utils.db2px(10);

    public PieChartView(Context context) {
        super(context);
    }

    public PieChartView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public PieChartView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        rectF.set(PAINDING, PAINDING, getMeasuredWidth() - PAINDING, getMeasuredWidth() - PAINDING);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        float startAngle = 0;
        for (int i = 0; i < sweepAngles.length; i++) {
            paint.setColor(COLORS[i % COLORS.length]);
            double offsetX = 0, offsetY = 0;
            if (offsetIndex == i) {
                double a = Math.toRadians(startAngle + sweepAngles[i] / 2);
                offsetX = Math.cos(a) * offset;
                offsetY = Math.sin(a) * offset;
            }
            rectF.offset((float) offsetX, (float) offsetY);
            canvas.drawArc(rectF, startAngle, sweepAngles[i], true, paint);
            rectF.offset((float) -offsetX, (float) -offsetY);
            startAngle += sweepAngles[i];
        }
    }
}
